﻿using Models.API.Param;
using Models.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using Web.Common;
using Web.Filters;

namespace Web.Controllers.API
{
    public class BillController : ApiController
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        /// <summary>
        /// 创建销售单
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult CreateBill(ChuKuDanForInsert model)
        {
            string strSQL;
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                return Json(result);
            }
            FreeADO.DBUtility.DbHelperSQLP db = new FreeADO.DBUtility.DbHelperSQLP(connectionString);

            if (string.IsNullOrWhiteSpace(model.BillCode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "BillCode不可为空";
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(model.EtypeId))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "EtypeId不可为空";
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(model.KtypeId))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "KtypeId不可为空";
                return Json(result);
            }

            //if (string.IsNullOrWhiteSpace(model.BtypeId))
            //{
            //    result.Type = AjaxResultType.Warning;
            //    result.Content = "BtypeId不可为空";
            //    return Json(result);
            //}

            DataTable dt = new DataTable();

            //查询职员ID
            strSQL = "select typeid,DtypeID,FullName from employee where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.EtypeId);
            dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            if (dt.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "职员ID不存在";
                return Json(result);
            }
            string Etypeid = dt.Rows[0]["typeid"].ToString();
            //职员姓名
            string EfullName = dt.Rows[0]["FullName"].ToString();
            string Dtypeid = dt.Rows[0]["DtypeID"].ToString();

            //查询仓库ID
            strSQL = "select typeid from stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.KtypeId);
            dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            if (dt.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "仓库ID不存在";
                return Json(result);
            }
            string Ktypeid = dt.Rows[0]["typeid"].ToString();

            //查询结算ID
            //strSQL = "select typeid from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.BtypeId);
            //string Btypeid = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["typeid"].ToString();

            //查询往来单位ID
            //string Btypeid = "";
            //strSQL = "select typeid from btype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.KtypeId);
            //dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            //if (dt.Rows.Count > 0)
            //{
            //    //往来单位编号
            //    Btypeid = dt.Rows[0]["typeid"].ToString();
            //}
            ////else {
            ////    strSQL = "select typeid from btype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.KtypeId);
            ////    dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            ////}


            //查询往来单位ID begin 2022-05-06
            string userCode = "wyy";
            if (!string.IsNullOrWhiteSpace(model.BtypeId))
            {
                userCode = model.BtypeId;
            }
            string Btypeid = "";
            string BfullName = "";
            string strSQL22 = "select typeid,FullName from btype where UserCode ='" + userCode + "'";
            DataTable dt22 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL22).Tables[0];
            if (dt22.Rows.Count > 0)
            {
                //往来单位编号
                Btypeid = dt22.Rows[0]["typeid"].ToString();
                BfullName = dt22.Rows[0]["FullName"].ToString();
            }
            //查询往来单位ID end


            //判断商品code重复
            strSQL = "select BillCode from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.BillCode);
            dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            if (dt.Rows.Count > 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "销售单ID:BillCode已存在";
                return Json(result);
            }

            #region 查询收款账户ID 2023-02-23
            string AtypeId = "";
            string strSQL23 = "select nId from Ac_Items where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.AtypeId);
            DataTable dt23 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL23).Tables[0];
            if (dt23.Rows.Count > 0)
            {
                //收款账户ID
                AtypeId = dt23.Rows[0]["nId"].ToString();
            }
            #endregion 


            try
            {
                string strBollDate = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                DateTime dtNow = Convert.ToDateTime(strBollDate);

                //获取BillCode
                //strSQL = "";
                //strSQL += "declare @code nvarchar(500)";
                //strSQL += " exec Gp_GetBillCode @BCode=@code output";
                //strSQL += " ,@BType=11";
                //strSQL += " ,@Month='" + (dtNow.Month <= 9 ? "0" + dtNow.Month.ToString(): dtNow.Month.ToString()) + "'";
                //strSQL += " ,@Day='" + (dtNow.Day <= 9 ? "0" + dtNow.Day.ToString() : dtNow.Day.ToString()) + "'";
                //strSQL += " ,@BillDate='" + dtNow.ToString("yyyy-MM-dd") + "'";
                //strSQL += " ,@BillFlag=N'BH'";
                //strSQL += " ,@STypeid='00001',@BillNumberId=N'-1'";
                //strSQL += " select @code as CODE";

                //string strBillCode = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["CODE"].ToString();


                string strComment = model.Comment;
                string proName = "", topComment = "";
                //int i = 0;

                if (model.Goods.Count == 1)
                {
                    foreach (var item in model.Goods)
                    {
                        //查询商品是否配件 00003
                        string strSQL1 = "select PtypeCategoryID from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.GoodID);
                        dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL1).Tables[0];
                        if (dt.Rows.Count > 0)
                        {
                            if (dt.Rows[0]["PtypeCategoryID"].ToString() == "00003")
                            {
                                topComment = "配件";
                            }
                        }
                    }
                }

                foreach (var item in model.Goods)
                {
                    if (item.IsGift == "0")
                    {
                        proName = item.Name;
                    }

                    if (!db.Exists("select CargoID from CargoType where deleted=0 and KtypeID='" + Ktypeid + "' and Comment='" + item.CargoCode + "'"))
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "CargoCode[" + item.CargoCode + "]不存在，或此仓库没有这个货位";
                        return Json(result);
                    }

                    //if (!string.IsNullOrWhiteSpace(item.IsGift))
                    //{
                    //    proName = item.Name;
                    //}
                    //else
                    //{
                    //    if (i == 0)
                    //    {
                    //        proName = item.Name;
                    //    }
                    //}
                    //i++;
                }


                    if (string.IsNullOrWhiteSpace(model.Comment))
                {
                    strComment = topComment + "销售【" + proName + "】等给【" + BfullName + "】：" + EfullName;
                }


                SqlParameter[] parameters = {
                    new SqlParameter("@BillDate",dtNow),//单据日期
                    new SqlParameter("@BillCode",model.BillCode),//单据编号
                    new SqlParameter("@BillType","11"),//单据类型
                    //new SqlParameter("@Comment",(string.IsNullOrWhiteSpace(model.Comment) ? "" : model.Comment.ToString())),//备注
                    new SqlParameter("@Comment",strComment),//备注
                    new SqlParameter("@AtypeId",AtypeId),//
                    new SqlParameter("@PtypeId",""),//商品ID
                    new SqlParameter("@BtypeId",SqlDbType.VarChar),//结算单位ID
                    new SqlParameter("@EtypeId",Etypeid),//职员ID
                    new SqlParameter("@KtypeId",Ktypeid),//仓库ID
                    new SqlParameter("@KtypeId2",""),//仓库ID 2 (仓库表usercode)
                    new SqlParameter("@IfCheck",'f'),//是否过账标识*
                    new SqlParameter("@CheckE",Etypeid),//制单人
                    new SqlParameter("@TotalMoney",model.Goods.Sum(p => p.Price * p.Number)),//单据金额
                    new SqlParameter("@TotalQty",model.Goods.Sum(p => p.Number)),//单据数量
                    new SqlParameter("@TotalInMoney",SqlDbType.Decimal),//收款金额14
                    new SqlParameter("@Tax","0.0"),//税率
                    new SqlParameter("@szPeriod",1),//会计期间
                    new SqlParameter("@Explain",""),//说明
                    new SqlParameter("@Draft",'1'),//草稿标识
                    new SqlParameter("@RedWord",'0'),//红冲标识
                    new SqlParameter("@STypeID","00001"),//分支机构ID
                    new SqlParameter("@DTypeID",Dtypeid),//部门ID
                    new SqlParameter("@completedate",null),//
                    new SqlParameter("@billstate",1),//
                    new SqlParameter("@ifmulaccount",SqlDbType.Int),//
                    new SqlParameter("@vipczmoney",SqlDbType.Decimal),//25
                    new SqlParameter("@otherinouttype",-1),//
                    new SqlParameter("@czbeforetimes",0),//
                    new SqlParameter("@PosBillType",SqlDbType.Int),//28
                    new SqlParameter("@TransportId",""),//
                    new SqlParameter("@IsFreightMoney",SqlDbType.Int),//
                    new SqlParameter("@FreightAddr",null),//
                    new SqlParameter("@FreightPerson",null),//
                    new SqlParameter("@FreightTel",null),//
                    new SqlParameter("@ShareMode",SqlDbType.Int),//34
                    new SqlParameter("@DEALBTYPEID",SqlDbType.VarChar),//35  往来单位
                    new SqlParameter("@cid",1),//
                    new SqlParameter("@rate",1),//
                    new SqlParameter("@ntotalmoney",model.Goods.Sum(p => p.Price * p.Number)),//合计
                    new SqlParameter("@ntotalinmoney",SqlDbType.Decimal),
                    new SqlParameter("@npreferencemoney","0"),//
                    new SqlParameter("@nvipczmoney",SqlDbType.Int),//41
                    new SqlParameter("@atypeid1","0000100006"),//
                    new SqlParameter("@billproperty",-1),//
                    new SqlParameter("@ncompletetotal",SqlDbType.Decimal),//44
                    new SqlParameter("@isini",false),//
                    new SqlParameter("@ATID",SqlDbType.Int),//46
                    new SqlParameter("@completetotal",SqlDbType.Decimal),//47
                    new SqlParameter("@IfCargo",SqlDbType.Int),//
                    new SqlParameter("@IfInvoice",SqlDbType.Int),//
                    new SqlParameter("@promoruleid",'0'),//
                    new SqlParameter("@beforepromobillnumberid",'0'),//

                    new SqlParameter("@WayBillCode",""),//
                    new SqlParameter("@Goodsnumber",""),//
                    new SqlParameter("@PackWay",""),//
                    new SqlParameter("@Tel",""),//
                    new SqlParameter("@Assessor",""),//
                    new SqlParameter("@IfAudit",""),//
                    new SqlParameter("@Audit_explain",""),//
                    new SqlParameter("@JieJianBillNumberID","-1"),//
                    new SqlParameter("@JieJianID","-1"),//
                    new SqlParameter("@BaoXiuID","-1"),//13002492380
                    new SqlParameter("@BaoXiuBillNumberID","-1"),//
                };

                //  parameters[6].Value = string.IsNullOrWhiteSpace(model.BtypeId) ? "02001" : model.BtypeId; //结算单位ID(零售客户)
                parameters[6].Value = Btypeid;
                parameters[14].Value = model.TotalinMoney;
                parameters[24].Value = 0;
                parameters[25].Value = 0;
                parameters[28].Value = 0;
                parameters[30].Value = 0;
                parameters[34].Value = 0;
                // parameters[35].Value = string.IsNullOrWhiteSpace(model.BtypeId) ? "02001" : model.BtypeId; //结算单位ID
                parameters[35].Value = Btypeid;
                parameters[39].Value = model.TotalinMoney;
                parameters[40].Value = 0;
                parameters[41].Value = 0;
                parameters[44].Value = 0;
                parameters[46].Value = 0;
                parameters[47].Value = 0;
                parameters[48].Value = 0;
                parameters[49].Value = 0;


                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_InsertBillIndex", parameters, out resultCount);

                strSQL = "";
                strSQL += "select BillNumberId from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.BillCode);
                dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
                if (dt.Rows.Count <= 0)
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "销售出库单插入错误";
                    return Json(result);
                }

                string BillNumberId = dt.Rows[0]["BillNumberId"].ToString();

                bool bo = true;

                if (BillNumberId.Length > 0)
                {
                    strSQL = "";
                    strSQL += "declare @b dbo.TBType_Sale ";

                    foreach (var item in model.Goods)
                    {
                        int CargoID = Convert.ToInt32(db.GetSingle("select CargoID from CargoType where deleted=0 and KtypeID='" + Ktypeid + "' and Comment='" + item.CargoCode + "'"));



                        //查询商品ID
                        string strSQL2 = "select typeid from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.GoodID);
                        dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL2).Tables[0];
                        if (dt.Rows.Count > 0)
                        {
                            string Ptypeid = dt.Rows[0]["typeid"].ToString();

                            strSQL += " insert into @b values(";
                            strSQL += " N'" + BillNumberId + "'";
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(Ptypeid);//商品ID
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Number.ToString());//单价
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());//数量
                            strSQL += ",1.000";
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());
                            strSQL += ",''";
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(((item.Price * item.Number)).ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(strBollDate);
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString());
                            strSQL += ",N'" + (string.IsNullOrWhiteSpace(item.Comment) ? "" : item.Comment.ToString()) + "'";
                            strSQL += ",N'-1'";
                            strSQL += ",N'0'";
                            strSQL += ",N'я" + item.Serial.Replace(",", "я") + @"я'";
                            strSQL += ",N'0'";
                            strSQL += ",N'" + item.GoodsNumber.ToString() + "'";
                            strSQL += ",N'" + (string.IsNullOrWhiteSpace(item.ProduceDate) ? "" : item.ProduceDate.ToString()) + "'";//生产日期2022-06-13添加
                            strSQL += ",N''";
                            strSQL += ",N''";
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.CostPrice.ToString());
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(Ktypeid);
                            strSQL += ",N'00001'";
                            strSQL += ",N'0.00'";
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString());
                            strSQL += ",N'0.00'";
                            strSQL += "," + CargoID;
                            //strSQL += ",N'" + item.CargoID + "'";
                            strSQL += ",N'1'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",NULL";
                            strSQL += ",N'1'";
                            strSQL += ",N'" + item.Number + "'";
                            strSQL += ",N'1.0000000000'";
                            strSQL += ",NULL";
                            strSQL += ",N'" + item.Price + "'";
                            strSQL += ",N'" + item.Price + "'";
                            strSQL += ",N'" + item.Price + "'";
                            strSQL += ",N'" + item.Price + "'";
                            strSQL += ",N'" + item.Price + "'";
                            strSQL += ",N'" + item.Price + "'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N''";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'接口自动生成'";
                            strSQL += ",N'" + (string.IsNullOrWhiteSpace(item.IsGift) ? "0" : item.IsGift) + "'";//IsGift
                            strSQL += ",N'0'";
                            strSQL += ",N'0.0000000000'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'1'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",NULL";
                            strSQL += ",NULL";
                            strSQL += ",N'" + Etypeid + "'";
                            strSQL += ",NULL";
                            strSQL += ",N''";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += " ) ";
                        }
                        else
                        {
                            bo = false;
                            result.Type = AjaxResultType.Warning;
                            result.Content = "商品ID不存在";
                            return Json(result);
                        }
                    }

                    strSQL += "exec Gp_InsertSaleBillDT @details=@b"; //SaleBill销售出库单
                    FreeADO.DBUtility.DbHelperSQL.ExecuteSqlConnstr(connectionString, strSQL);

                    strSQL = "";
                    strSQL += "insert into Custom_Billindex(BillId,BillType,SysDiy1_head,SysDiy2_head)values(";
                    strSQL += " N'" + BillNumberId + "'";
                    strSQL += " ,N'11' ";
                    strSQL += " ,N'" + model.CustomName + "'";
                    strSQL += " ,N'" + model.CustomTel + "'";
                    strSQL += " )";
                    FreeADO.DBUtility.DbHelperSQL.ExecuteSqlConnstr(connectionString, strSQL);

                    #region 2023-03-13 新增序列号和无忧价格

                    foreach (var goodItem in model.Goods)
                    {
                        string serial = "я" + goodItem.Serial.Replace(",", "я") + @"я";
                        //通过 BillNumberId,ptypeId 查询 SaleBill 的 ID
                        string strSQL3 = string.Format(@"select s.ID from SaleBill s where s.BillNumberId='{0}' and s.Serial='{1}'", BillNumberId, serial);

                        dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL3).Tables[0];
                        if (dt.Rows.Count > 0)
                        {
                            string detailid = dt.Rows[0]["ID"].ToString();
                            // 插入 Custom_BillDetails 表
                            SqlParameter[] parameter = {
                                    new SqlParameter("@BillId", BillNumberId),
                                    new SqlParameter("@Detailid", detailid),
                                    new SqlParameter("@BillType", 11),
                                    new SqlParameter("@SysDiy1", goodItem.Serial),
                                    new SqlParameter("@SysDiy3", goodItem.WyPrice),
                                    new SqlParameter("@SysDiy17", ""),
                                    new SqlParameter("@SysDiy18", ""),
                                    new SqlParameter("@SysDiy19",""),
                                    new SqlParameter("@SysDiy20", ""),
                                    new SqlParameter("@SysDiy21", ""),
                                    new SqlParameter("@SysDiy22", ""),
                                    new SqlParameter("@SysDiy23", ""),
                                    new SqlParameter("@SysDiy24", ""),
                                    new SqlParameter("@SysDiy25", ""),
                                    new SqlParameter("@SysDiy26", "")
                                };
                            int rowsAffected = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "GP_InsertCustom_BillDetails", parameter, out rowsAffected);
                        }
                    }
                    #endregion


                    //strSQL = "";
                    //strSQL += " exec GP_SaveBillCode_Seed";
                    //strSQL += " @intBillNumberID=" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(BillNumberId);
                    //strSQL += ",@dBillDate=" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(dtNow.ToString("yyyy-MM-dd"));
                    //strSQL += ",@intBillType=11";
                    //strSQL += ",@strBillCode=" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(strBillCode);
                    //FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL);
                    List<ErpHelper.V993.MultAtypeModel> ml = new List<ErpHelper.V993.MultAtypeModel>();
                    ErpHelper.V993.MultAtypeModel mm = new ErpHelper.V993.MultAtypeModel();
                    mm.AtypeId = AtypeId;
                    mm.BillNumberID = int.Parse(BillNumberId);
                    mm.BillType = 11;
                    mm.NTotalMoney = model.TotalinMoney;
                    mm.Total = model.TotalinMoney;
                    ml.Add(mm);
                    ErpHelper.V993.ErpHelper.InsertMultAtype(db, ml);


                }

                if (bo)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "成功";
                    result.Data = "";
                    result.TotalRows = 0;
                }
                else
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "成功,但明细中包含未查询到的商品ID";
                    result.Data = "";
                    result.TotalRows = 0;
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 创建销售单-无忧过账
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult CreateBillSeed(ChuKuDanForInsert model)
        {
            string pr = "";
            string strSQL;
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                return Json(result);
            }
            FreeADO.DBUtility.DbHelperSQLP db = new FreeADO.DBUtility.DbHelperSQLP(connectionString);
            if (string.IsNullOrWhiteSpace(model.BillCode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "BillCode不可为空";
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(model.EtypeId))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "EtypeId不可为空";
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(model.KtypeId))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "KtypeId不可为空";
                return Json(result);
            }
            //if (string.IsNullOrWhiteSpace(model.AtypeId))
            //{
            //    result.Type = AjaxResultType.Warning;
            //    result.Content = "AtypeId不可为空";
            //    return Json(result);
            //}

            //if (string.IsNullOrWhiteSpace(model.BtypeId))
            //{
            //    result.Type = AjaxResultType.Warning;
            //    result.Content = "BtypeId不可为空";
            //    return Json(result);
            //}

            DataTable dt = new DataTable();

            //查询职员ID
            strSQL = "select typeid,DtypeID,FullName from employee where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.EtypeId);
            dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            if (dt.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "职员ID不存在";
                return Json(result);
            }
            string Etypeid = dt.Rows[0]["typeid"].ToString();
            //职员姓名
            string EfullName = dt.Rows[0]["FullName"].ToString();
            string Dtypeid = dt.Rows[0]["DtypeID"].ToString();

            //查询仓库ID
            strSQL = "select typeid from stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.KtypeId);
            dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            if (dt.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "仓库ID不存在";
                return Json(result);
            }
            string Ktypeid = dt.Rows[0]["typeid"].ToString();

            //查询结算ID
            //strSQL = "select typeid from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.BtypeId);
            //string Btypeid = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["typeid"].ToString();

            //查询往来单位ID
            //string Btypeid = "";
            //strSQL = "select typeid from btype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.KtypeId);
            //dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            //if (dt.Rows.Count > 0)
            //{
            //    //往来单位编号
            //    Btypeid = dt.Rows[0]["typeid"].ToString();
            //}
            ////else {
            ////    strSQL = "select typeid from btype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.KtypeId);
            ////    dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            ////}


            //查询往来单位ID begin 2022-05-06
            string Btypeid = "";
            string BfullName = "";
            string strSQL22 = "select typeid,FullName from btype where UserCode ='wyy'";
            DataTable dt22 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL22).Tables[0];
            if (dt22.Rows.Count > 0)
            {
                //往来单位编号
                Btypeid = dt22.Rows[0]["typeid"].ToString();
                BfullName = dt22.Rows[0]["FullName"].ToString();
            }
            //查询往来单位ID end

            #region 查询收款账户ID 2023-02-23
            string AtypeId = "";
            string strSQL23 = "select nId from Ac_Items where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.AtypeId);
            DataTable dt23 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL23).Tables[0];
            if (dt23.Rows.Count > 0)
            {
                //收款账户ID
                AtypeId = dt23.Rows[0]["nId"].ToString();
            }
            #endregion 


            //判断商品code重复
            strSQL = "select BillCode from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.BillCode);
            dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            if (dt.Rows.Count > 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "销售单ID:BillCode已存在";
                return Json(result);
            }


            try
            {
                string strBollDate = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                DateTime dtNow = Convert.ToDateTime(strBollDate);

                //获取BillCode
                //strSQL = "";
                //strSQL += "declare @code nvarchar(500)";
                //strSQL += " exec Gp_GetBillCode @BCode=@code output";
                //strSQL += " ,@BType=11";
                //strSQL += " ,@Month='" + (dtNow.Month <= 9 ? "0" + dtNow.Month.ToString(): dtNow.Month.ToString()) + "'";
                //strSQL += " ,@Day='" + (dtNow.Day <= 9 ? "0" + dtNow.Day.ToString() : dtNow.Day.ToString()) + "'";
                //strSQL += " ,@BillDate='" + dtNow.ToString("yyyy-MM-dd") + "'";
                //strSQL += " ,@BillFlag=N'BH'";
                //strSQL += " ,@STypeid='00001',@BillNumberId=N'-1'";
                //strSQL += " select @code as CODE";

                //string strBillCode = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["CODE"].ToString();

                model.TotalQty = model.Goods.Sum(p => p.Number);
                model.TotalMoney = 0;
                string strComment = model.Comment;
                string proName = "";
                //string giftName = "";
                int i = 0;
                int giftQty = 0;//赠品数量
                foreach (var item in model.Goods)
                {
                    model.TotalMoney += Convert.ToDecimal((item.Price * item.Number).ToString("F2"));

                    //查询商品IsItGift
                    string strSQL2 = "select IsItGift from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.GoodID);
                    dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL2).Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        if ((string.IsNullOrWhiteSpace(dt.Rows[0]["IsItGift"].ToString()) || dt.Rows[0]["IsItGift"].ToString() == "False") && int.Parse(item.IsGift) > 0)
                            giftQty++;
                    }

                    if (!string.IsNullOrWhiteSpace(item.IsGift))
                    {
                        proName = item.Name;
                    }
                    else
                    {
                        if (i == 0)
                        {
                            proName = item.Name;
                        }
                    }
                    i++;
                    if (!db.Exists("select CargoID from CargoType where deleted=0 and KtypeID='" + Ktypeid + "' and Comment='" + item.CargoCode + "'"))
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "CargoCode[" + item.CargoCode + "]不存在，或此仓库没有这个货位";
                        return Json(result);
                    }

                }

                if ("197".Equals(model.StoreId.ToString()))
                {
                    if (giftQty > 0)
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "单据里有不可赠送的商品！";
                        return Json(result);
                    }
                }
                //else
                //    pr = "0";

                if (string.IsNullOrWhiteSpace(model.Comment))
                {
                    strComment = "销售【" + proName + "】等给【" + BfullName + "】：" + EfullName;
                }

                SqlParameter[] parameters = {
                    new SqlParameter("@BillDate",dtNow),//单据日期
                    new SqlParameter("@BillCode",model.BillCode),//单据编号
                    new SqlParameter("@BillType","11"),//单据类型

                    //new SqlParameter("@Comment",strComment),//2023-02-22 新增&修改
                    new SqlParameter("@Comment",(string.IsNullOrWhiteSpace(model.Comment) ? "摘要" : model.Comment.ToString())),//备注 2023-02-22 注释
                    new SqlParameter("@AtypeId",AtypeId),//2023-02-23 注释
                    //new SqlParameter("@AtypeId",AtypeId),//2023-02-23 新增&修改
                    new SqlParameter("@PtypeId",""),//商品ID
                    new SqlParameter("@BtypeId",SqlDbType.VarChar),//结算单位ID
                    new SqlParameter("@EtypeId",Etypeid),//职员ID
                    new SqlParameter("@KtypeId",Ktypeid),//仓库ID
                    new SqlParameter("@KtypeId2",""),//仓库ID 2 (仓库表usercode)
                    new SqlParameter("@IfCheck",'f'),//是否过账标识*
                    new SqlParameter("@CheckE",Etypeid),//制单人
                    new SqlParameter("@TotalMoney",model.TotalMoney),//单据金额
                    new SqlParameter("@TotalQty",model.TotalQty),//单据数量
                    new SqlParameter("@TotalInMoney",SqlDbType.Decimal),//收款金额14
                    new SqlParameter("@Tax","0.0"),//税率
                    new SqlParameter("@szPeriod",1),//会计期间
                    new SqlParameter("@Explain",""),//说明
                    new SqlParameter("@Draft",'1'),//草稿标识
                    new SqlParameter("@RedWord",'0'),//红冲标识
                    new SqlParameter("@STypeID","00001"),//分支机构ID
                    new SqlParameter("@DTypeID",Dtypeid),//部门ID
                    new SqlParameter("@completedate",null),//
                    new SqlParameter("@billstate",1),//
                    new SqlParameter("@ifmulaccount",SqlDbType.Int),//
                    new SqlParameter("@vipczmoney",SqlDbType.Decimal),//25
                    new SqlParameter("@otherinouttype",-1),//
                    new SqlParameter("@czbeforetimes",0),//
                    new SqlParameter("@PosBillType",SqlDbType.Int),//28
                    new SqlParameter("@TransportId",""),//
                    new SqlParameter("@IsFreightMoney",SqlDbType.Int),//
                    new SqlParameter("@FreightAddr",null),//
                    new SqlParameter("@FreightPerson",null),//
                    new SqlParameter("@FreightTel",null),//
                    new SqlParameter("@ShareMode",SqlDbType.Int),//34
                    new SqlParameter("@DEALBTYPEID",SqlDbType.VarChar),//35
                    new SqlParameter("@cid",1),//
                    new SqlParameter("@rate",1),//
                    new SqlParameter("@ntotalmoney",model.TotalMoney),//合计
                    //new SqlParameter("@ntotalinmoney",SqlDbType.Int),//2023-02-23 注释
                    new SqlParameter("@ntotalinmoney",SqlDbType.Decimal),//收现金额 <--> 原币收现金额2023-02-23 新增
                    new SqlParameter("@npreferencemoney",SqlDbType.Int),//
                    new SqlParameter("@nvipczmoney",SqlDbType.Int),//41
                    new SqlParameter("@atypeid1","0000100006"),//
                    new SqlParameter("@billproperty",-1),//
                    new SqlParameter("@ncompletetotal",SqlDbType.Decimal),//44
                    new SqlParameter("@isini",false),//
                    new SqlParameter("@ATID",SqlDbType.Int),//46
                    new SqlParameter("@completetotal",SqlDbType.Decimal),//47
                    new SqlParameter("@IfCargo",SqlDbType.Int),//
                    new SqlParameter("@IfInvoice",SqlDbType.Int),//
                    new SqlParameter("@promoruleid",'0'),//
                    new SqlParameter("@beforepromobillnumberid",'0'),//

                    new SqlParameter("@WayBillCode",""),//
                    new SqlParameter("@Goodsnumber",""),//
                    new SqlParameter("@PackWay",""),//
                    new SqlParameter("@Tel",""),//
                    new SqlParameter("@Assessor",""),//
                    new SqlParameter("@IfAudit",""),//
                    new SqlParameter("@Audit_explain",""),//
                    new SqlParameter("@JieJianBillNumberID","-1"),//
                    new SqlParameter("@JieJianID","-1"),//
                    new SqlParameter("@BaoXiuID","-1"),//
                    new SqlParameter("@BaoXiuBillNumberID","-1"),//
                };

                //parameters[6].Value = string.IsNullOrWhiteSpace(model.BtypeId) ? "02001" : model.BtypeId; //结算单位ID(零售客户)
                parameters[6].Value = Btypeid; //结算单位ID(零售客户) 2022-05-06 修改固定ID
                parameters[14].Value = model.TotalinMoney;
                parameters[24].Value = 0;
                parameters[25].Value = 0;
                parameters[28].Value = 0;
                parameters[30].Value = 0;
                parameters[34].Value = 0;
                //parameters[35].Value = string.IsNullOrWhiteSpace(model.BtypeId) ? "02001" : model.BtypeId; //结算单位ID
                parameters[35].Value = Btypeid; //结算单位ID
                parameters[39].Value = model.TotalinMoney;
                parameters[40].Value = 0;
                parameters[41].Value = 0;
                parameters[44].Value = 0;
                parameters[46].Value = 0;
                parameters[47].Value = 0;
                parameters[48].Value = 0;
                parameters[49].Value = 0;


                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_InsertBillIndex", parameters, out resultCount);

                strSQL = "";
                strSQL += "select BillNumberId from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.BillCode);
                dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
                if (dt.Rows.Count <= 0)
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "销售出库单插入错误";
                    return Json(result);
                }

                string BillNumberId = dt.Rows[0]["BillNumberId"].ToString();

                bool bo = true;

                if (BillNumberId.Length > 0)
                {


                    strSQL = "";
                    strSQL += "declare @b dbo.TBType_Sale ";

                    foreach (var item in model.Goods)
                    {
                        int CargoID = Convert.ToInt32(db.GetSingle("select CargoID from CargoType where deleted=0 and KtypeID='" + Ktypeid + "' and Comment='" + item.CargoCode + "'"));

                        //查询商品ID
                        string strSQL2 = "select typeid from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.GoodID);
                        dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL2).Tables[0];
                        if (dt.Rows.Count > 0)
                        {
                            string Ptypeid = dt.Rows[0]["typeid"].ToString();

                            strSQL += " insert into @b values(";
                            strSQL += " N'" + BillNumberId + "'";                                                                                      //[BillNumberId] [numeric](10, 0) NULL,
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(Ptypeid);//商品ID                                                //[PtypeId] [varchar](50) NULL,
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Number.ToString());//单价                                   //[Qty] [numeric](24, 10) NULL,
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());//数量                                    //[SalePrice] [numeric](24, 10) NULL,
                            strSQL += ",1.000";                                                                                                        //[Discount] [numeric](24, 10) NULL,
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());                                          //[DiscountPrice] [numeric](24, 10) NULL,
                            strSQL += ",''";                                                                                                           //[Jobnumber] [varchar](20) NULL,
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(((item.Price * item.Number)).ToString("F2"));                    //[Total] [numeric](24, 10) NULL,
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(strBollDate);                                                    //[OutFactoryDate] [datetime] NULL DEFAULT
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());                                          //[TaxPrice] [numeric](24, 10) NULL,
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString("F2"));                      //[TaxTotal] [numeric](24, 10) NULL,
                            strSQL += ",N'" + (string.IsNullOrWhiteSpace(item.Comment) ? "" : item.Comment.ToString()) + "'";                          //[Comment] [varchar](255) NULL,
                            strSQL += ",N'-1'";                                                                                                        //[OrderID] [int] NULL,
                            strSQL += ",N'0'";                                                                                                         //[intisUnitTow] [int] NULL,
                            strSQL += ",N'я" + item.Serial.Replace(",", "я") + @"я'";                                                               //[Serial] [varchar](max) NULL,
                            strSQL += ",N'0'";                                                                                                         //[InputCostPrice] [numeric](24, 10) NULL 
                            strSQL += ",N'" + item.GoodsNumber.ToString() + "'";                                                                       //[GoodsNumber] [varchar](100) NULL DEFAUL
                            strSQL += ",N'" + item.ProduceDate + "'";//生产日期参数 2022-06-13添加                                                     //[ProduceDate] [varchar](50) NULL DEFAULT
                            strSQL += ",N''";                                                                                                          //[ValidDate] [varchar](50) NULL DEFAULT (
                            strSQL += ",N''";                                                                                                          //[GoodsBTypeID] [varchar](50) NULL DEFAUL
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.CostPrice.ToString());                                      //[GoodsCostPrice] [numeric](24, 10) NULL 
                            strSQL += ",N'0'";                                                                                                         //[HandZeroCost] [int] NULL DEFAULT ((0)),
                            strSQL += ",N'0'";                                                                                                         //[Tax] [numeric](24, 10) NULL DEFAULT ((0
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString("F2"));                      //[SaleTotal] [numeric](24, 10) NULL DEFAU
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(Ktypeid);                                                        //[KTypeID] [varchar](50) NULL DEFAULT (''
                            strSQL += ",N'00001'";                                                                                                     //[STypeID] [varchar](50) NULL,
                            strSQL += ",N'0.00'";                                                                                                      //[TaxMoney] [numeric](24, 10) NULL,
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());                                          //[NSalePrice] [numeric](24, 10) NULL,
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString("F2"));                      //[NSaleTotal] [numeric](24, 10) NULL,
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());                                          //[NDiscountPrice] [numeric](24, 10) NULL,
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString("F2"));                      //[NTotal] [numeric](24, 10) NULL,
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());                                          //[NTaxPrice] [numeric](24, 10) NULL,
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString("F2"));                      //[NTaxTotal] [numeric](24, 10) NULL,
                            strSQL += ",N'0.00'";                                                                                                      //[NTaxMoney] [numeric](24, 10) NULL,
                            strSQL += ","+ CargoID;                                                                                                    //[CargoId] [int] NULL,
                            strSQL += ",N'1'";                                                                                                         //[UnitId] [int] NULL,
                            strSQL += ",N'0'";                                                                                                         //[NUnitId] [int] NULL,
                            strSQL += ",N'0'";                                                                                                         //[NQty] [numeric](24, 10) NULL,
                            strSQL += ",N'0'";                                                                                                         //[UnitRate] [numeric](24, 10) NULL,
                            strSQL += ",NULL";                                                                                                         //[NUnitMsg] [varchar](50) NULL,
                            strSQL += ",N'1'";                                                                                                         //[MUnitId] [int] NULL,
                            strSQL += ",N'" + item.Number + "'";                                                                                       //[MQty] [numeric](24, 10) NULL,
                            strSQL += ",N'1.0000000000'";                                                                                              //[MUnitRate] [numeric](24, 10) NULL,
                            strSQL += ",NULL";                                                                                                         //[MUnitMsg] [varchar](50) NULL,
                            strSQL += ",N'" + item.Price + "'";                                                                                        //[MSalePrice] [numeric](24, 10) NULL,
                            strSQL += ",N'" + item.Price + "'";                                                                                        //[MDiscountPrice] [numeric](24, 10) NULL,
                            strSQL += ",N'" + item.Price + "'";                                                                                        //[MTaxPrice] [numeric](24, 10) NULL,
                            strSQL += ",N'" + item.Price + "'";                                                                                        //[CurMSalePrice] [numeric](24, 10) NULL,
                            strSQL += ",N'" + item.Price + "'";                                                                                        //[CurMDiscountPrice] [numeric](24, 10) NU
                            strSQL += ",N'" + item.Price + "'";                                                                                        //[CurMTaxPrice] [numeric](24, 10) NULL,
                            strSQL += ",N'0'";                                                                                                         //[ItemId] [bigint] NULL,
                            strSQL += ",N'0'";                                                                                                         //[IsCombined] [int] NULL,
                            strSQL += ",N'0'";                                                                                                         //[CompleteQTY] [numeric](24, 10) NULL,
                            strSQL += ",N'0'";                                                                                                         //[CompleteTotal] [numeric](24, 10) NULL,
                            strSQL += ",N'0'";                                                                                                         //[NCompleteTotal] [numeric](24, 10) NULL,
                            strSQL += ",N''";                                                                                                          //[entryCode] [varchar](200) NULL,
                            strSQL += ",N'0'";                                                                                                         //[InvoiceQty] [numeric](24, 10) NULL,
                            strSQL += ",N'0'";                                                                                                         //[InvoiceMoney] [numeric](24, 10) NULL,
                            strSQL += ",N'0'";                                                                                                         //[NInvoiceMoney] [numeric](24, 10) NULL,
                            strSQL += ",N'接口自动生成'";                                                                                              //[PriceSource] [varchar](200) NULL,
                            strSQL += ",N'" + (string.IsNullOrWhiteSpace(item.IsGift) ? "0" : item.IsGift) + "'";//IsGift                              //[IsGift] [int] NULL,
                            strSQL += ",N'0'";                                                                                                         //[BeforePromoID] [int] NULL,
                            strSQL += ",N'0.0000000000'";                                                                                              //[ReferPrice] [numeric](24, 10) NULL,
                            strSQL += ",N'0'";                                                                                                         //[PriceStyle] [int] NOT NULL DEFAULT ((0)
                            strSQL += ",N'0'";                                                                                                         //[PromoType] [int] NOT NULL DEFAULT ((0))
                            strSQL += ",N'0'";                                                                                                         //[OMBillID] [int] NULL,
                            strSQL += ",N'0'";                                                                                                         //[LendBillID] [numeric](10, 0) NULL,
                            strSQL += ",N'0'";                                                                                                         //[LendBillNumberID] [numeric](10, 0) NULL
                            strSQL += ",N'0'";                                                                                                         //[ID] [int] NULL,
                            strSQL += ",N'1'";                                                                                                         //[ShowOrder] [int] NULL,
                            strSQL += ",N'0'";                                                                                                         //[DiyID] [int] NULL,
                            strSQL += ",N'0'";                                                                                                         //[iscombination] [bit] NULL DEFAULT ((0))
                            strSQL += ",NULL";                                                                                                         //[combinationptypeid] [varchar](200) NULL
                            strSQL += ",NULL";                                                                                                         //[pindexid] [varchar](300) NULL,
                            strSQL += ",N'" + Etypeid + "'";                                                                                           //[ETypeID] [varchar](100) NULL,
                            strSQL += ",NULL";                                                                                                         //[PromonIds] [varchar](1000) NULL,
                            strSQL += ",N''";                                                                                                          //[CouponCode] [varchar](200) NULL,
                            strSQL += ",N'0'";                                                                                                         //[IsPromotion] [int] NULL,
                            strSQL += ",N'0'";                                                                                                         //[IsVipPoint] [int] NULL,
                            strSQL += ",N'0'";                                                                                                         //[PriceDetailId] [int] NULL DEFAULT ((0))
                            strSQL += ",N'0'";                                                                                                         //[PriceRuleId] [int] NULL DEFAULT ((0))
                            strSQL += " ) ";                                                                                                           //

                        }
                        else
                        {
                            bo = false;
                            result.Type = AjaxResultType.Warning;
                            result.Content = "商品ID不存在";
                            return Json(result);
                        }
                    }

                    strSQL += "exec Gp_InsertSaleBillDT @details=@b"; //SaleBill销售出库单
                    FreeADO.DBUtility.DbHelperSQL.ExecuteSqlConnstr(connectionString, strSQL);

                    strSQL = "";
                    strSQL += "insert into Custom_Billindex(BillId,BillType,SysDiy1_head,SysDiy2_head)values(";
                    strSQL += " N'" + BillNumberId + "'";
                    strSQL += " ,N'11' ";
                    strSQL += " ,N'" + model.CustomName + "'";
                    strSQL += " ,N'" + model.CustomTel + "'";
                    strSQL += " )";
                    FreeADO.DBUtility.DbHelperSQL.ExecuteSqlConnstr(connectionString, strSQL);

                    //strSQL = "";
                    //strSQL += " exec GP_SaveBillCode_Seed";
                    //strSQL += " @intBillNumberID=" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(BillNumberId);
                    //strSQL += ",@dBillDate=" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(dtNow.ToString("yyyy-MM-dd"));
                    //strSQL += ",@intBillType=11";
                    //strSQL += ",@strBillCode=" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(strBillCode);
                    //FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL);
                    List<ErpHelper.V993.MultAtypeModel> ml = new List<ErpHelper.V993.MultAtypeModel>();
                    ErpHelper.V993.MultAtypeModel mm = new ErpHelper.V993.MultAtypeModel();
                    mm.AtypeId = AtypeId;
                    mm.BillNumberID = int.Parse(BillNumberId);
                    mm.BillType = 11;
                    mm.NTotalMoney = model.TotalinMoney;
                    mm.Total = model.TotalinMoney;
                    ml.Add(mm);
                    ErpHelper.V993.ErpHelper.InsertMultAtype(db, ml);


                    //无忧商品需要的直接过账，执行以下代码
                    SqlParameter[] parmsyy = {
                    new SqlParameter("@nBillID",BillNumberId),//单号
                    new SqlParameter("@szCheckMan",Etypeid),//制单人
                    new SqlParameter("@chvOpID","00001"),//当前操作员
                    new SqlParameter("@billtype","11"),//单据类型
                    new SqlParameter("@szPID",""),
                    new SqlParameter("@Ret",0)  };

                    parmsyy[4].Direction = ParameterDirection.Output;
                    parmsyy[5].Direction = ParameterDirection.Output;

                    int ii = 0;
                    FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_NewAuditing", parmsyy, out ii);

                    pr = parmsyy[5].Value.ToString();


                }

                if (bo == true && pr == "0")
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "成功";
                    result.Data = pr;
                    result.TotalRows = 0;
                }
                else
                {
                    string returnMessage = "";
                    switch (int.Parse(pr))
                    {
                        case -11:
                            returnMessage = "单据往来科目不存在，生成凭证失败！";
                            break;
                        case -13:
                            returnMessage = "单据已经生成过凭证，生成凭证失败！";
                            break;
                        case -210:
                            returnMessage = "不存在默认模板，生成凭证失败！";
                            break;
                        case -211:
                            returnMessage = "凭证写入出错，生成凭证失败！";
                            break;
                        case -212:
                            returnMessage = "单据往来科目获取失败，凭证生成失败!";
                            break;
                        case -213:
                            returnMessage = "模板中有会计科目外币核算与单据币种不符，生成凭证失败!";
                            break;
                        case -214:
                            returnMessage = "模板对应单据金额全部为0，无法生成凭证！\n如单据金额字段不是全部为0，请检查模板后重新生成！\n模板中存在项目的请同时检查项目管理是否配置项目对应科目。";
                            break;
                        case -216:
                            returnMessage = "辅助核算获取失败，生成凭证失败！";
                            break;
                        case -217:
                            returnMessage = "凭证不符合保存规则，生成凭证失败，请检查模板！";
                            break;
                        case -218:
                            returnMessage = "凭证字不存在，生成凭证失败！";
                            break;
                        case -219:
                            returnMessage = "每行凭证分录必有摘要，模板不符，生成凭证失败！";
                            break;
                        case -220:
                            returnMessage = "模板不存在，生成凭证失败！";
                            break;
                        case -221:
                            returnMessage = "生成凭证要求录入现金流量，自动生成失败！";
                            break;
                        case -222:
                            returnMessage = "生成凭证科目不全，请检查项目设置！";
                            break;
                        case -223:
                            returnMessage = "您使用的是试用版，凭证数据不能大于200";
                            break;
                        case -224:
                            returnMessage = "配置要求每行分录必有摘要，生成凭证时分录存在摘要为空\n生成失败，请检查凭证模板或单据中【说明】\\【摘要】是否为空";
                            break;
                        case -225:
                            returnMessage = "凭证分录第一行摘要为空，请检查凭证模板或单据中字段【说明】\\【摘要】是否为空";
                            break;
                        case -226:
                            returnMessage = "当前单据生成的会计凭证无对应会计期间，请先结帐到下一年度再生成";
                            break;
                        case -227:
                            returnMessage = "总账未开账，不能生成凭证";
                            break;
                        case -228:
                            returnMessage = "生成凭证中有科目被停用，无法生成凭证";
                            break;
                        case -229:
                            returnMessage = "单据非资金调拨单，无法处理相应业务";
                            break;
                        case -230:
                            returnMessage = "出纳当前期间与总账期间不一致，不能生成凭证";
                            break;
                    }
                    if (returnMessage != "")
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "成功";
                        result.Data = pr;
                        result.TotalRows = 0;
                    }
                    else
                    {
                        result.Type = AjaxResultType.Fail;
                        result.Content = "草稿生成成功,但过账失败！";
                        result.Data = pr;
                        result.TotalRows = 0;
                    }
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }



        /// <summary>
        /// 创建结算单位
        /// </summary>
        /// <param name="UserCode">商品ID</param>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult InsertBtype([FromBody] Models.API.Param.StockModel entity)
        {
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(entity.UserCode.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "UserCode不可为空";
                result.Data = "Warning";
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(entity.FullName.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "FullName不可为空";
                result.Data = "Warning";
                return Json(result);
            }

            try
            {
                SqlParameter[] parameters = {
                    new SqlParameter("@Parid","00001"),//父节点ID
                    new SqlParameter("@DbName","btype"),//
                    new SqlParameter("@UserCode",entity.UserCode.ToString()),//编号
                    new SqlParameter("@FullName",entity.FullName.ToString()),//名称
                    new SqlParameter("@Name",""),//
                    new SqlParameter("@Area",""),//
                    new SqlParameter("@TelAndAddress",""),//
                    new SqlParameter("@PostCode",""),//
                    new SqlParameter("@Person",""),//
                    new SqlParameter("@TaxNumber",""),//
                    new SqlParameter("@bankandacount",""),//
                    new SqlParameter("@Artotal00",0),//
                    new SqlParameter("@Aptotal00",0),//
                    new SqlParameter("@Comment",""),//
                    //new SqlParameter("@Client [Bit]=1,",""),//
                    //new SqlParameter("@ARLimit  NUMERIC(24, 10) =0,",""),//
                    //new SqlParameter("@ARLimitTime  NUMERIC(24, 10) =99999,",""),//
                    //new SqlParameter("@PaymentLTime NUMERIC(24, 10) =99999, ",""),//
                    new SqlParameter("@Tel1",""),//
                    new SqlParameter("@Tel2",""),//
                    new SqlParameter("@Tel3",""),//
                    new SqlParameter("@WWW",""),//
                    new SqlParameter("@Email",""),//
                    new SqlParameter("@Fax",""),//
                    new SqlParameter("@Bank",""),//
                    new SqlParameter("@BankName",""),//
                    new SqlParameter("@LinkMan1",""),//
                    new SqlParameter("@LinkSex1",""),//
                    new SqlParameter("@LinkBirthDay1",null),//
                    new SqlParameter("@LinkJob1",""),//
                    new SqlParameter("@LinkCall1",""),//
                    new SqlParameter("@LinkTel1",""),//
                    new SqlParameter("@LinkMobile1",""),//
                    new SqlParameter("@LinkEMail1",""),//
                    new SqlParameter("@LinkPost1",""),//
                    new SqlParameter("@LinkAddress1",""),//
                    new SqlParameter("@LinkComment1",""),//
                    new SqlParameter("@LinkMan2",""),//
                    new SqlParameter("@LinkSex2",null),//
                    new SqlParameter("@LinkBirthDay2",null),//
                    new SqlParameter("@LinkJob2",""),//
                    new SqlParameter("@LinkCall2",""),//
                    new SqlParameter("@LinkTel2",""),//
                    new SqlParameter("@LinkMobile2",""),//
                    new SqlParameter("@LinkEMail2",""),//
                    new SqlParameter("@LinkPost2",""),//
                    new SqlParameter("@LinkAddress2",""),//
                    new SqlParameter("@LinkComment2",""),//
                    new SqlParameter("@CreateDate",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),//
                    new SqlParameter("@SaleZeKou",0),//
                    new SqlParameter("@BuyZeKou",0),//
                    new SqlParameter("@PyCode",""),//
                    new SqlParameter("@Price",""),//
                    new SqlParameter("@AreaTypeID",""),//

                    new SqlParameter("@valeditprice",""),//
                    new SqlParameter("@denominatedid",""),//
                    new SqlParameter("@backlimitday",""),//
                    new SqlParameter("@backpercent",""),//
                    new SqlParameter("@cid",""),//
                };

                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_InsertB", parameters, out resultCount);

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.TotalRows = resultCount;
                result.Data = "OK";
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 查询指定时间的 销售和退货信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult GetInOutstocktable([FromBody] Models.Common.TimeInterval timeInterval)
        {
            Result<IList<InOutstocktableModel>> result = new Result<IList<InOutstocktableModel>>();
            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }

            if (timeInterval == null)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "参数对象不可为空";
                result.Data = null;
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(timeInterval.StartDate.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "StartDate不可为空";
                result.Data = null;
                return Json(result);
            }
            if (string.IsNullOrWhiteSpace(timeInterval.EndDate.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "EndDate不可为空";
                result.Data = null;
                return Json(result);
            }

            try
            {
                string sql = @"declare @StartDate datetime = '" + timeInterval.StartDate + "',@EndDate datetime ='" + timeInterval.EndDate + @"'
select i.ID,i.BillNumberId,gp.Serial,bill.billcode,bill.BillDate posttime,i.BillType,bn.BillName,i.PtypeId,p.UserCode PtypeCode,p.FullName PtypeName,i.etypeid,e.UserCode EtypeCode,e.FullName EtypeName,
i.KtypeId,Stock.UserCode KCode,Stock.FullName Kname,i.Qty,i.Price,i.Total,i.CostPrice,i.CostTotal,p.ParId,(select FullName from Ptype where typeId = p.ParId) Category,i.IsGift,cb.SysDiy1_head,cb.SysDiy2_head
from InOutstocktable as i 
inner join BillIndex as bill on bill.BillNumberId = i.BillNumberId
inner join BillName as bn on bn.Billtype = i.BillType
inner join ptype as p on p.typeId = i.PtypeId
inner join employee as e on e.typeId = i.EtypeId
inner join Stock on Stock.typeId = i.KtypeId
left join gp_inoutPtypeSerial as gp on gp.BillNumberid = i.BillNumberId and gp.detailID=i.ID
left join Custom_BillIndex as cb on cb.BillId = i.BillNumberId
where i.BillDate between @StartDate and @EndDate and i.BillType in (11,34,45)
order by i.BillNumberId asc";
                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, sql).Tables[0];

                if (dt != null)
                {
                    IList<InOutstocktableModel> list = new List<InOutstocktableModel>();
                    foreach (DataRow dr in dt.Rows)
                    {
                        InOutstocktableModel mode = new InOutstocktableModel();
                        mode.ID = Convert.ToInt32(dr["ID"]);
                        mode.BillNumberId = dr["BillNumberId"].ToString();
                        mode.Serial = dr["Serial"].ToString();
                        mode.billcode = dr["billcode"].ToString();
                        mode.posttime = dr["posttime"].ToString();
                        mode.BillType = Convert.ToInt32(dr["BillType"]);
                        mode.BillName = dr["BillName"].ToString();
                        mode.PtypeId = dr["PtypeId"].ToString();
                        mode.PtypeCode = dr["PtypeCode"].ToString();
                        mode.PtypeName = dr["PtypeName"].ToString();
                        mode.EtypeId = dr["etypeid"].ToString();
                        mode.EtypeCode = dr["EtypeCode"].ToString();
                        mode.EtypeName = dr["EtypeName"].ToString();
                        mode.KtypeId = dr["KtypeId"].ToString();
                        mode.KCode = dr["KCode"].ToString();
                        mode.Qty = Convert.ToDecimal(dr["Qty"]);
                        mode.Price = Convert.ToDecimal(dr["Price"]);
                        mode.Total = Convert.ToDecimal(dr["Total"]);
                        mode.CostPrice = Convert.ToDecimal(dr["CostPrice"]);
                        mode.CostTotal = Convert.ToDecimal(dr["CostTotal"]);
                        mode.IsGift = Convert.ToInt32(dr["IsGift"]);
                        mode.Kname = dr["Kname"].ToString();
                        mode.Category = dr["Category"].ToString();
                        mode.SysDiy1_head = dr["SysDiy1_head"].ToString();
                        mode.SysDiy2_head = dr["SysDiy2_head"].ToString();

                        list.Add(mode);
                    }
                    result.Type = AjaxResultType.Success;
                    result.Content = "成功";
                    result.Data = list;
                }
                else
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "成功";
                    result.Data = null;
                }
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }

            return Json(result);
        }

        [HttpPost]
        public IHttpActionResult GetTest()
        {
            Result<DataTable> result = new Result<DataTable>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                return Json(result);
            }

            string strSQL = "select top 2 *  from gp_CruPtypeSerial";
            DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            result.Type = AjaxResultType.Success;
            result.Content = "成功";
            result.Data = dt;

            return Json(result);
        }
        /// <summary>
        /// 修改销售出库草稿
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult UpdateBill(ChuKuDanForInsert model)
        {
            string strSQL;
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                return Json(result);
            }

            FreeADO.DBUtility.DbHelperSQLP db = new FreeADO.DBUtility.DbHelperSQLP(connectionString);
            if (string.IsNullOrWhiteSpace(model.BillCode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "BillCode不可为空";
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(model.EtypeId))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "EtypeId不可为空";
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(model.KtypeId))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "KtypeId不可为空";
                return Json(result);
            }

            DataTable dt = new DataTable();

            //判断是否是草稿
            int BillNumberId = 0;
            strSQL = "select BillNumberId,draft,ifcheck,Comment,atypeid from BillIndex where draft=1 and ifcheck='f' and  BillCode = '" + model.BillCode + "'";
            dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            if (dt.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "没有找到对应的草稿";
                return Json(result);
            }
            model.Comment = dt.Rows[0]["Comment"].ToString();//2022年11月21日 手机宝盒增加对此列的不修改
            BillNumberId = Convert.ToInt32(dt.Rows[0]["BillNumberId"]);

            model.AtypeId = dt.Rows[0]["atypeid"].ToString();//2023-03-09 对此列不修改

            //查询职员ID
            strSQL = "select typeid,DtypeID from employee where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.EtypeId);
            dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            if (dt.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "职员ID不存在";
                return Json(result);
            }
            string Etypeid = dt.Rows[0]["typeid"].ToString();
            string Dtypeid = dt.Rows[0]["DtypeID"].ToString();

            //查询仓库ID
            strSQL = "select typeid from stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.KtypeId);
            dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            if (dt.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "仓库ID不存在";
                return Json(result);
            }
            string Ktypeid = dt.Rows[0]["typeid"].ToString();

            //查询往来单位ID 
            string userCode = "wyy";
            if (!string.IsNullOrWhiteSpace(model.BtypeId))
            {
                userCode = model.BtypeId;
            }
            string Btypeid = "";
            string strSQL22 = "select typeid from btype where UserCode ='" + userCode + "'";
            DataTable dt22 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL22).Tables[0];
            if (dt22.Rows.Count > 0)
            {
                //往来单位编号
                Btypeid = dt22.Rows[0]["typeid"].ToString();
            }

            foreach (var item in model.Goods)
            {

                if (!db.Exists("select CargoID from CargoType where deleted=0 and KtypeID='" + Ktypeid + "' and Comment='" + item.CargoCode + "'"))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "CargoCode[" + item.CargoCode + "]不存在，或此仓库没有这个货位";
                    return Json(result);
                }
                if (!db.Exists("select Pid from ptype where sonnum=0 and deleted=0 and UserCode='" + item.GoodID + "'"))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "商品编号[" + item.GoodID + "]不存在";
                    return Json(result);
                }

            }



            try
            {
                string strBollDate = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                DateTime dtNow = Convert.ToDateTime(strBollDate);

                SqlParameter[] parameters = {
                    new SqlParameter("@BillNumberID", BillNumberId),//1
                new SqlParameter("@BillDate", dtNow),//2
                new SqlParameter("@BillCode", model.BillCode),//3
                new SqlParameter("@BillType", 11),//4
                //new SqlParameter("@ATypeID", "1"),//5 2023-03-09 注释
                new SqlParameter("@ATypeID",model.AtypeId),//5  2023-03-09 修改
                new SqlParameter("@PTypeID", ""),
                new SqlParameter("@BTypeID", Btypeid),//7
                new SqlParameter("@ETypeID", Etypeid),
                new SqlParameter("@KTypeID", Ktypeid),//9·
                new SqlParameter("@KTypeID2", ""),
                new SqlParameter("@IfCheck", "f"),//11
                new SqlParameter("@CheckE", Etypeid),
                new SqlParameter("@TotalMoney",model.Goods.Sum(p => p.Price * p.Number)),//13
                new SqlParameter("@TotalInMoney",model.Goods.Sum(p => p.CostPrice * p.Number)),
                new SqlParameter("@TotalQty",model.Goods.Sum(p => p.Number)),//15
                new SqlParameter("@Tax","0.0000000000"),//税率//16
                new SqlParameter("@Period", 1),
                new SqlParameter("@Explain", ""),//18
                new SqlParameter("@RedWord", "0"),
                new SqlParameter("@Draft", 1),//20
                new SqlParameter("@OrderID", "0"),
                new SqlParameter("@Comment", model.Comment),//22
                new SqlParameter("@WayBillCode", ""),
                new SqlParameter("@Goodsnumber",""),//24
                new SqlParameter("@PackWay", ""),
                new SqlParameter("@Tel", ""),//26
                new SqlParameter("@preferencemoney", "0"),
                new SqlParameter("@AlertDay", 9999),//28
                new SqlParameter("@Assessor", string.Empty),
                new SqlParameter("@IfAudit", string.Empty),//30
                new SqlParameter("@Audit_Explain", string.Empty),
                new SqlParameter("@Dtypeid", Dtypeid),//32
                new SqlParameter("@VipCardID", -1),
                new SqlParameter("@KTypeID3", ""),//34
                new SqlParameter("@LinkMan", ""),
                new SqlParameter("@LinkTel", ""),//36
                new SqlParameter("@LinkAddr", ""),
                new SqlParameter("@wxManID", ""),//38
                new SqlParameter("@JieJianBillNumberID", -1),
                new SqlParameter("@JieJianID", -1),//40
                new SqlParameter("@BaoXiuBillNumberID", -1),
                new SqlParameter("@BaoXiuID", -1),//42
                new SqlParameter("@BuyDate", ""),
                new SqlParameter("@Serial", ""),//44
                new SqlParameter("@wxTotal", "0.0000000000"),
                new SqlParameter("@ErrDes", ""),//46
                new SqlParameter("@ifHideJieJian", false),
                new SqlParameter("@ifWX", false),//48
                new SqlParameter("@IfBargainOn", false),
                new SqlParameter("@STypeID", "00001"),//50
                new SqlParameter("@FromBillNumberID", "0"),
                new SqlParameter("@CostSale", "0"),//52
                new SqlParameter("@completedate", null),
                new SqlParameter("@billstate", 1),//54
                new SqlParameter("@ifmulaccount", false),
                new SqlParameter("@otherinouttype", -1),//56
                new SqlParameter("@czbeforetimes", 0),
                new SqlParameter("@posbilltype", "0"),//58
                new SqlParameter("@updateE", "00001"),
                new SqlParameter("@sharemode", "0"),//60
                new SqlParameter("@TransportId", ""),
                new SqlParameter("@IsFreightMoney", "0"),//62
                new SqlParameter("@FreightAddr", ""),
                new SqlParameter("@freightperson", ""),//64
                new SqlParameter("@freighttel", ""),
                new SqlParameter("@ModifyAuditBill", 0),//66
                new SqlParameter("@uf1", ""),
                new SqlParameter("@uf2", ""),//68
                new SqlParameter("@uf3", ""),
                new SqlParameter("@uf4", ""),//70
                new SqlParameter("@uf5", ""),
                new SqlParameter("@DEALBTYPEID", Btypeid),//72
                new SqlParameter("@cid", 1),
                new SqlParameter("@rate", 1),//74
                new SqlParameter("@ntotalmoney",model.Goods.Sum(p => p.Price * p.Number)),
                //new SqlParameter("@ntotalinmoney", 0),//76 2023-03-09 注释
                new SqlParameter("@ntotalinmoney", model.TotalinMoney),//76 2023-03-09 修改
                new SqlParameter("@npreferencemoney", 0),
                new SqlParameter("@nvipczmoney", 0),//78
                new SqlParameter("@ATYPEID1", "0000100006"),
                new SqlParameter("@billproperty", -1),//80
                new SqlParameter("@ncompletetotal", 44),
                new SqlParameter("@isini", false),//82
                new SqlParameter("@ATID", "0"),
                new SqlParameter("@completetotal", "0"),//84
                new SqlParameter("@IfCargo", "0"),
                new SqlParameter("@IfInvoice", "0"),//86
                new SqlParameter("@invoicemoney", "0"),
                new SqlParameter("@ninvoicemoney", "0"),//88
                new SqlParameter("@AssetBusinessTypeId", "0"),//业务类型id
                new SqlParameter("@promoruleid", '0'),//90
                new SqlParameter("@beforepromobillnumberid", "0"),
                new SqlParameter("@promotionmsg", ""),//92
                new SqlParameter("@STypeID2", ""),
                new SqlParameter("@ifconfirm", "0"),//94
                new SqlParameter("@FeeDeductType", "0"),
                new SqlParameter("@TransferType", 1),//96
                new SqlParameter("@Discount", "1.0000000000"),
                new SqlParameter("@DeliveryAddress", ""),//98
                new SqlParameter("@AdPriceType", "0"),
                new SqlParameter("@checkSave", ""),//100
                new SqlParameter("@chargeofftotal", 0),
                new SqlParameter("@nchargeofftotal", 0),//102
                new SqlParameter("@ChargeOffType", "0"),
                new SqlParameter("@ChargeOffBtypeid", ""),//104
                new SqlParameter("@IsLend", false),
                new SqlParameter("@WarehouseOutDay", 9999),//106
                new SqlParameter("@StockInDeadline", 9999),
                new SqlParameter("@IsNeedTransport", 0),//108
                new SqlParameter("@iscombinationstyle", "0"),
                new SqlParameter("@transportno", null),//110
                new SqlParameter("@transporterid", "0"),
                new SqlParameter("@transporterfullname", null),//112
                new SqlParameter("@shipperfullname", null),
                new SqlParameter("@shipperperson", null),//114
                new SqlParameter("@shippertel", null),
                new SqlParameter("@totalfreight", "0"),//116
                new SqlParameter("@ntotalfreight", "0"),
                new SqlParameter("@paytag", 0),//支付方式//118
                new SqlParameter("@PromonIds", 0),
                new SqlParameter("@isByBrandarType", null),//120
                new SqlParameter("@NewPosBill", 0),
                new SqlParameter("@PayOnTheSpot", "0"),//122
                new SqlParameter("@allowinvoicing", 1)
            };

                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_UpdateBillIndex", parameters, out resultCount);
                bool bo = true;

                if (BillNumberId != 0)
                {
                    strSQL = "";
                    strSQL += "declare @b dbo.TBType_Sale ";

                    foreach (var item in model.Goods)
                    {
                        int CargoID = Convert.ToInt32(db.GetSingle("select CargoID from CargoType where deleted=0 and KtypeID='" + Ktypeid + "' and Comment='" + item.CargoCode + "'"));

                        //查询商品ID
                        string strSQL2 = "select typeid from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.GoodID);
                        dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL2).Tables[0];
                        if (dt.Rows.Count > 0)
                        {
                            string Ptypeid = dt.Rows[0]["typeid"].ToString();

                            strSQL += " insert into @b values(";
                            strSQL += " N'" + BillNumberId + "'";
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(Ptypeid);//商品ID
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Number.ToString());//单价
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());//数量
                            strSQL += ",1.000";
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());
                            strSQL += ",''";
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(((item.Price * item.Number)).ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(strBollDate);
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString());
                            strSQL += ",N'" + (string.IsNullOrWhiteSpace(item.Comment) ? "" : item.Comment.ToString()) + "'";
                            strSQL += ",N'-1'";
                            strSQL += ",N'0'";
                            strSQL += ",N'я" + item.Serial.Replace(",", "я") + @"я'";
                            strSQL += ",N'0'";
                            strSQL += ",N'" + item.GoodsNumber.ToString() + "'";
                            strSQL += ",N'" + (string.IsNullOrWhiteSpace(item.ProduceDate) ? "" : item.ProduceDate.ToString()) + "'";//生产日期2022-06-13添加
                            strSQL += ",N''";
                            strSQL += ",N''";
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.CostPrice.ToString());
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(Ktypeid);
                            strSQL += ",N'00001'";
                            strSQL += ",N'0.00'";
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(item.Price.ToString());
                            strSQL += "," + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr((item.Price * item.Number).ToString());
                            strSQL += ",N'0.00'";
                            //strSQL += ",(select top 1 CargoID from CargoType where KtypeID = " + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(Ktypeid) + "  order by IsDefault desc)";
                            //strSQL += ",(select CargoID from CargoType where KtypeID = " + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(Ktypeid) + ")";
                            strSQL += ",N'" + CargoID + "'";
                            strSQL += ",N'1'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",NULL";
                            strSQL += ",N'1'";
                            strSQL += ",N'" + item.Number + "'";
                            strSQL += ",N'1.0000000000'";
                            strSQL += ",NULL";
                            strSQL += ",N'" + item.Price + "'";
                            strSQL += ",N'" + item.Price + "'";
                            strSQL += ",N'" + item.Price + "'";
                            strSQL += ",N'" + item.Price + "'";
                            strSQL += ",N'" + item.Price + "'";
                            strSQL += ",N'" + item.Price + "'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N''";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'接口自动生成'";
                            strSQL += ",N'" + (string.IsNullOrWhiteSpace(item.IsGift) ? "0" : item.IsGift) + "'";//IsGift
                            strSQL += ",N'0'";
                            strSQL += ",N'0.0000000000'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'1'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",NULL";
                            strSQL += ",NULL";
                            strSQL += ",N'" + Etypeid + "'";
                            strSQL += ",NULL";
                            strSQL += ",N''";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += ",N'0'";
                            strSQL += " ) ";

                        }
                        else
                        {
                            bo = false;
                            result.Type = AjaxResultType.Warning;
                            result.Content = "商品ID不存在";
                            return Json(result);
                        }
                    }

                    strSQL += "exec Gp_InsertSaleBillDT @details=@b"; //SaleBill销售出库单
                    FreeADO.DBUtility.DbHelperSQL.ExecuteSqlConnstr(connectionString, strSQL);

                    strSQL = "";
                    strSQL += "insert into Custom_Billindex(BillId,BillType,SysDiy1_head,SysDiy2_head)values(";
                    strSQL += " N'" + BillNumberId + "'";
                    strSQL += " ,N'11' ";
                    strSQL += " ,N'" + model.CustomName + "'";
                    strSQL += " ,N'" + model.CustomTel + "'";
                    strSQL += " )";
                    FreeADO.DBUtility.DbHelperSQL.ExecuteSqlConnstr(connectionString, strSQL);

                    #region 2023-03-13 新增序列号和无忧价格

                    foreach (var goodItem in model.Goods)
                    {
                        string serial = "я" + goodItem.Serial.Replace(",", "я") + @"я";
                        //通过 BillNumberId,serial 查询 SaleBill 的 ID
                        string strSQL3 = string.Format(@"select s.ID from SaleBill s where s.BillNumberId='{0}' and s.Serial='{1}'", BillNumberId, serial);

                        dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL3).Tables[0];
                        if (dt.Rows.Count > 0)
                        {
                            string detailid = dt.Rows[0]["ID"].ToString();
                            // 插入 Custom_BillDetails 表
                            SqlParameter[] parameter = {
                                    new SqlParameter("@BillId", BillNumberId),
                                    new SqlParameter("@Detailid", detailid),
                                    new SqlParameter("@BillType", 11),
                                    new SqlParameter("@SysDiy1", goodItem.Serial),
                                    new SqlParameter("@SysDiy3", goodItem.WyPrice),
                                    new SqlParameter("@SysDiy17", ""),
                                    new SqlParameter("@SysDiy18", ""),
                                    new SqlParameter("@SysDiy19",""),
                                    new SqlParameter("@SysDiy20", ""),
                                    new SqlParameter("@SysDiy21", ""),
                                    new SqlParameter("@SysDiy22", ""),
                                    new SqlParameter("@SysDiy23", ""),
                                    new SqlParameter("@SysDiy24", ""),
                                    new SqlParameter("@SysDiy25", ""),
                                    new SqlParameter("@SysDiy26", "")
                                };
                            int rowsAffected = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "GP_InsertCustom_BillDetails", parameter, out rowsAffected);
                        }
                    }
                    #endregion
                }

                if (bo)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "成功";
                    result.Data = "";
                    result.TotalRows = 0;
                }
                else
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "成功,但明细中包含未查询到的商品ID";
                    result.Data = "";
                    result.TotalRows = 0;
                }
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }

            return Json(result);
        }
        /// <summary>
        /// 根据单据号查询单据状态
        /// </summary>
        /// <param name="billStatus"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult GetBillStatus(BillStatus billStatus)
        {
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(billStatus.BillCode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "BillCode不能为空";
                result.Data = "Warning";
                return Json(result);
            }
            try
            {
                string strSQL = "select BillNumberId,BillDate,ifcheck,draft from BillIndex where RedWord != 2 and BillCode='" + billStatus.BillCode + "'";
                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    string ifcheck = dr["ifcheck"].ToString();
                    bool draft = Convert.ToBoolean(dr["draft"]);

                    if (!draft)
                    {
                        switch (ifcheck)
                        {
                            case "f":
                                result.Type = AjaxResultType.Warning;
                                result.Content = "不是草稿，未过账";
                                break;
                            case "t":
                                result.Type = AjaxResultType.Warning;
                                result.Content = "不是草稿,已过账";
                                break;
                        }
                    }
                    else
                    {
                        switch (ifcheck)
                        {
                            case "f":
                                result.Type = AjaxResultType.Success;
                                result.Content = "是草稿，未过账";
                                break;
                            case "t":
                                result.Type = AjaxResultType.Warning;
                                result.Content = "是草稿，已过账";
                                break;
                        }
                    }
                    result.Data = "";
                    result.TotalRows = 0;
                }
                else
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "BillCode无效，没有找到对应单据";
                    result.Data = "Warning";
                    return Json(result);
                }
                return Json(result);
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
        }

        /// <summary>
        /// 创建采购单
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult CreateBuyBill(BuyBillClass model)
        {
            Result<string> result = new Result<string>() { Type = AjaxResultType.Success, Content = "成功", Data = "", TotalRows = 0 };
            
            try
            {
                int BillType = 34;
                string connectionString = "";
                string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
                if (!"OK".Equals(msg))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = msg;
                    result.Data = "Error";
                    return Json(result);
                }
                FreeADO.DBUtility.DbHelperSQLP db = new FreeADO.DBUtility.DbHelperSQLP(connectionString);
                if (string.IsNullOrWhiteSpace(model.BillCode))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "BillCode不可为空";
                    return Json(result);
                }
                if (db.Exists("select billnumberid from BillIndex where BillCode='" + model.BillCode + "'"))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "BillCode已经存在";
                    return Json(result);
                }
                if (string.IsNullOrWhiteSpace(model.BillDate))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "BillDate不可为空";
                    return Json(result);
                }
                try
                {
                    model.BillDate = Convert.ToDateTime(model.BillDate).ToString("yyyy-MM-dd");
                }
                catch
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "BillDate必须为日期型";
                    return Json(result);
                }
                if (string.IsNullOrWhiteSpace(model.EtypeCode))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "EtypeCode不可为空";
                    return Json(result);
                }
                if (!db.Exists("select count(*) from employee where deleted=0  and sonnum=0 and UserCode= '" + model.EtypeCode + "'"))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "EtypeCode[" + model.EtypeCode + "]不存在";
                    return Json(result);
                }
                string EtypeID = db.GetSingle("select typeid from employee where deleted=0  and sonnum=0 and UserCode= '" + model.EtypeCode + "'").ToString();

                if (string.IsNullOrWhiteSpace(model.DtypeCode))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "DtypeCode不可为空";
                    return Json(result);
                }
                if (!db.Exists("select count(*) from Department where deleted=0  and sonnum=0 and UserCode= '" + model.DtypeCode + "'"))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "DtypeCode[" + model.DtypeCode + "]不存在";
                    return Json(result);
                }
                string DtypeID = db.GetSingle("select typeid from Department where deleted=0  and sonnum=0 and UserCode= '" + model.DtypeCode + "'").ToString();

                if (string.IsNullOrWhiteSpace(model.StockCode))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "StockCode不可为空";
                    return Json(result);
                }
                if (!db.Exists("select count(*) from Stock where deleted=0  and sonnum=0 and UserCode= '" + model.StockCode + "'"))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "StockCode[" + model.StockCode + "]不存在";
                    return Json(result);
                }
                string KtypeID = db.GetSingle("select typeid from Stock where deleted=0  and sonnum=0 and UserCode= '" + model.StockCode + "'").ToString();
                string KtypeName = db.GetSingle("select FullName from Stock where deleted=0  and sonnum=0 and UserCode= '" + model.StockCode + "'").ToString();

                if (string.IsNullOrWhiteSpace(model.BtypeCode))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "BtypeCode不可为空";
                    return Json(result);
                }
                if (!db.Exists("select count(*) from Btype where deleted=0  and sonnum=0 and UserCode= '" + model.BtypeCode + "'"))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "BtypeCode[" + model.BtypeCode + "]不存在";
                    return Json(result);
                }
                string BtypeID = db.GetSingle("select typeid from Btype where deleted=0  and sonnum=0 and UserCode= '" + model.BtypeCode + "'").ToString();

                List<ErpHelper.V993.BuyBillModel> goodslist = new List<ErpHelper.V993.BuyBillModel>();
                foreach (var item in model.Details)
                {
                    if (string.IsNullOrWhiteSpace(item.PtypeCode))
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "PtypeCode不可为空";
                        return Json(result);
                    }
                    if (!db.Exists("select count(*) from Ptype where deleted=0  and sonnum=0 and UserCode= '" + item.PtypeCode + "'"))
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "PtypeCode[" + item.PtypeCode + "]不存在";
                        return Json(result);
                    }
                    string PtypeID = db.GetSingle("select typeid from Ptype where deleted=0  and sonnum=0 and UserCode= '" + item.PtypeCode + "'").ToString();
                    if (string.IsNullOrWhiteSpace(item.UnitCode))
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "PtypeCode不可为空";
                        return Json(result);
                    }
                    if (!db.Exists("select count(*) from PType_Units_Ext as a inner join PType_Units as b on a.UnitsId=b.UnitsId  where a.PtypeID='" + PtypeID + "' and b.UserCode='" + item.UnitCode + "'"))
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "UnitCode[" + item.UnitCode + "]不存在，或此商品没有这个单位";
                        return Json(result);
                    }
                    DataTable udt = db.Query("select a.PtypeID,a.UnitsId,a.Rate,b.UserCode,b.FullName from PType_Units_Ext as a inner join PType_Units as b on a.UnitsId=b.UnitsId  where a.PtypeID='" + PtypeID + "' and b.UserCode='" + item.UnitCode + "'").Tables[0];
                    int UnitsId = Convert.ToInt32(udt.Rows[0]["UnitsId"]);
                    decimal UnitRate = Convert.ToDecimal(udt.Rows[0]["Rate"]);
                    int BaseUnitsID = Convert.ToInt32(db.GetSingle("select baseUnitId from ptype where typeId='" + PtypeID + "'"));

                    if (db.GetSingle("select IfSerial from Ptype where deleted=0  and sonnum=0 and UserCode= '" + item.PtypeCode + "'").ToString() == "1")
                    {
                        if (item.Qty * UnitRate != item.Serial.Count)
                        {
                            result.Type = AjaxResultType.Error;
                            result.Content = "PtypeCode[" + item.PtypeCode + "]此商品强制序列号，序列号数量与销售数量不等";
                            return Json(result);
                        }
                    }
                    if (item.Serial.Count>0)
                    {
                        if (Convert.ToInt32(db.GetSingle("SELECT count(*) FROM gp_CruPtypeSerial where State=1 and Serial in(select a from dbo.f_split('" + string.Join(",", item.Serial) + "',','))")) > 0)
                        {
                            result.Type = AjaxResultType.Error;
                            result.Content = "PtypeCode[" + item.PtypeCode + "]有在库的序列号";
                            return Json(result);
                        }
                    }
                    if (string.IsNullOrWhiteSpace(item.CargoCode))
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "CargoCode不可为空";
                        return Json(result);
                    }
                    if (!db.Exists("select CargoID from CargoType where deleted=0 and KtypeID='" + KtypeID + "' and Comment='" + item.CargoCode + "'"))
                    {
                        string CargoUserCode = KtypeName + "-" + item.CargoCode;
                        while (Convert.ToInt32(db.GetSingle("select count(*) from CargoType where UserCode='"+ CargoUserCode + "' or FullName='" + CargoUserCode + "'"))>0)
                        {
                            CargoUserCode = CargoUserCode + DateTime.Now.ToString("sss");
                        }
                        ErpHelper.V993.ErpHelper.CargoTypeEdit(db, 0,CargoUserCode , CargoUserCode, item.CargoCode, KtypeID, "ADD");
                        //result.Type = AjaxResultType.Error;
                        //result.Content = "CargoCode[" + item.CargoCode + "]不存在，或此仓库没有这个货位";
                        //return Json(result);
                    }
                    int CargoID = Convert.ToInt32(db.GetSingle("select CargoID from CargoType where deleted=0 and KtypeID='" + KtypeID + "' and Comment='" + item.CargoCode + "'"));

                    ErpHelper.V993.BuyBillModel gm = new ErpHelper.V993.BuyBillModel();
                    gm.PTypeID = PtypeID;
                    gm.Qty = item.Qty * UnitRate;
                    gm.MQty = item.Qty;
                    gm.SalePrice = item.Price / UnitRate;
                    gm.Total = gm.Qty * gm.SalePrice;//折后金额
                    gm.IsGift = gm.SalePrice == 0 ? 1 : 0;
                    gm.Discount = 1;
                    gm.DiscountPrice = gm.SalePrice;
                    gm.Tax = item.Tax;
                    gm.TaxPrice = gm.SalePrice * (1 + gm.Tax);
                    gm.TaxTotal = gm.TaxPrice * gm.Qty;
                    gm.TaxMoney = gm.TaxTotal - gm.Total;
                    gm.OrderID = -1;
                    gm.SaleTotal = gm.Total;//折前金额
                    gm.KTypeID = KtypeID;
                    gm.STypeID = "00001";
                    gm.NSalePrice = gm.SalePrice;
                    gm.NSaleTotal = gm.SaleTotal;
                    gm.NDiscountPrice = gm.DiscountPrice;
                    gm.NTotal = gm.Total;
                    gm.NTaxPrice = gm.TaxPrice;
                    gm.NTaxTotal = gm.TaxTotal;
                    gm.NTaxMoney = gm.TaxMoney;
                    gm.UnitId = BaseUnitsID;
                    gm.MUnitId = UnitsId;
                    gm.MUnitRate = UnitRate;
                    gm.MSalePrice = item.Price;
                    gm.MDiscountPrice = gm.MSalePrice;
                    gm.MTaxPrice = gm.MSalePrice * (1 + gm.Tax);
                    gm.CurMSalePrice = gm.MSalePrice;
                    gm.CurMDiscountPrice = gm.MSalePrice;
                    gm.CurMTaxPrice = gm.MTaxPrice;
                    gm.CargoId = CargoID;
                    gm.ShowOrder = model.Details.IndexOf(item) + 1;
                    gm.PriceSource = "手工输入";
                    gm.Serial = string.Join("я", item.Serial);
                    goodslist.Add(gm);
                }
                List<ErpHelper.V993.MultAtypeModel> ml = new List<ErpHelper.V993.MultAtypeModel>();
                foreach (var item in model.MultAtype)
                {
                    ErpHelper.V993.MultAtypeModel mm = new ErpHelper.V993.MultAtypeModel();
                    if (Convert.ToInt32(db.GetSingle("select COUNT(*) from Ac_Items where UserCode='" + item.AtypeCode + "' and deleted=0  and sonnum=0")) == 0)
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "付款账户不存在[" + item.AtypeCode + "]。";
                        return Json(result);
                    }
                    mm.AtypeId = db.GetSingle("select nid from Ac_Items where UserCode='" + item.AtypeCode + "' and deleted=0  and sonnum=0").ToString();
                    mm.Total = item.Total;
                    mm.Comment = item.Comment;
                    mm.BillType = BillType;
                    mm.atypecomment = "";
                    mm.CouponCode = "";
                    mm.NTotalMoney = mm.Total;
                    mm.TradeNo = "";
                    mm.vipcardid = "-1";
                    mm.viptotal = 0;
                    mm.yhType = 0;
                    mm.PayType = 0;
                    ml.Add(mm);
                }

                ErpHelper.V993.BillIndexParam bi = new ErpHelper.V993.BillIndexParam();
                bi.Comment = model.Comment;
                bi.Explain = model.Explain;
                bi.BillCode = model.BillCode;
                bi.BillDate = Convert.ToDateTime(model.BillDate);
                bi.BtypeId = BtypeID;
                bi.EtypeId = EtypeID;
                bi.DtypeId = DtypeID;
                bi.CheckE = "00001";
                bi.TotalMoney = goodslist.Sum(p => p.Total);
                bi.TotalQty = goodslist.Sum(p => p.Qty);
                bi.STypeID ="00001";
                bi.KtypeId = KtypeID;
                bi.BillType = BillType;
                bi.IfCheck = "f";
                bi.TotalInMoney = ml.Sum(p => p.Total);
                bi.szPeriod = 1;
                bi.Draft = true;
                bi.AlertDay = 9999;
                bi.VipCardID = -1;
                bi.JieJianBillNumberID = "-1";
                bi.JieJianID = "-1";
                bi.BaoXiuBillNumberID = "-1";
                bi.BaoXiuID = "-1";
                bi.completedate = Convert.ToDateTime("9999-12-31 23:59:59.997");
                bi.billstate = 1;
                bi.otherinouttype = -1;
                bi.DEALBTYPEID = bi.BtypeId;
                bi.cid = 1;
                bi.rate = 1;
                bi.ntotalmoney = bi.TotalMoney;
                bi.ntotalinmoney = bi.TotalInMoney;
                bi.billproperty = -1;
                bi.TransferType = 1;
                bi.Discount = 1;
                bi.yapiorderid = "0";
                bi.WarehouseOutDay = 9999;
                bi.StockInDeadline = 9999;
                bi.allowinvoicing = 1;
                bi.IfAudit = "";
                bi.atypeid1 = "000020000300001";
                bi.Tax = 0;
                int BillNumberID = ErpHelper.V993.ErpHelper.InsertBillIndex(db, bi);
                if (BillNumberID <= 0)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "采购入库单主表插入失败，错误码：" + BillNumberID;
                    return Json(result);
                }
                foreach (var item in goodslist)
                {
                    item.BillNumberID = BillNumberID;
                }
                ErpHelper.V993.ErpHelper.InsertBuyBillDT(db, goodslist);
                foreach (var item in ml)
                {
                    item.BillNumberID = BillNumberID;
                }
                ErpHelper.V993.ErpHelper.InsertMultAtype(db, ml);

                var re = ErpHelper.V993.ErpHelper.Auditing(db, BillNumberID, bi.CheckE, "00001", 34);
                if (re.Type == ErpHelper.V993.AjaxResultType.Success || re.Type == ErpHelper.V993.AjaxResultType.Warning)
                {

                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "采购入库单编号：[" + bi.BillCode + "]" + re.Content;
                    return Json(result);
                }



            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

    }
}